//
//  CTPickImageViewController.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/5/15.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTPickImageViewController.h"
#import "CTAdjustImageViewController.h"

//view
#import "CTPickImageView.h"
//logic

//function
#import "CTDebugManager.h"
#import "CTAppLanguage.h"
#import "CTAppInfo.h"
#import "CTRemindView.h"
#import "CTImageProcessing.h"
#import "MobClick.h"

//model
#import "CTPublishItems.h"

//frame work
#import <AssetsLibrary/AssetsLibrary.h>


typedef void (^SaveImageCompletion)();



@interface CTPickImageViewController ()<CTPickImageViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    CTPickImageView * pickImageView;
    
    NSMutableArray * albumArray;
    NSMutableArray * albumFullScreenArray;
    NSMutableArray * albumItemsArray;
    
    ALAssetsLibrary* library;
    
    BOOL isGroupEnumerAtion;
    
    CTAlbumItem * currentPickedItem;
}

@end

@implementation CTPickImageViewController
@synthesize type;
- (void)dealloc
{
    pickImageView = nil;
    albumArray = nil;
    albumItemsArray = nil;
    library = nil;
    currentPickedItem = nil;

    
    [CTDebugManager showDebugLogInfo:@"dealloc : CTPickImageViewController Is Removed!!!"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.view.backgroundColor = [UIColor whiteColor];
        albumArray = [NSMutableArray arrayWithCapacity:0];
        albumFullScreenArray = [NSMutableArray arrayWithCapacity:0];
        albumItemsArray = [NSMutableArray arrayWithCapacity:0];
        
        isGroupEnumerAtion = NO;
    }
    return self;
}


-(void)viewDidAppear:(BOOL)animated
{
    //统计
    [MobClick beginLogPageView:@"CTPickImageViewController"];
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    //统计
    [MobClick endLogPageView:@"CTPickImageViewController"];
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    pickImageView = [[CTPickImageView alloc] init];
    pickImageView.delegate = self;
    [self.view addSubview:pickImageView];
    
    //初始化相册数组
    [self initAlbumData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




-(void)reloadAlbumDetailData
{
    
}


#pragma mark - view delegate -

-(void)nextStepAction:(CTPickImageView *)view withImg:(NSString *)imgUrl
{
    [library assetForURL:[NSURL URLWithString:imgUrl] resultBlock:^(ALAsset *asset){
        self.hidesBottomBarWhenPushed = YES;
        
        CTAdjustImageViewController * adjustImageVC = [[CTAdjustImageViewController alloc] init];
        if (type == CTPickImageViewControllerTypeSetHead)
        {
            adjustImageVC.type = CTAdjustImageViewControllerTypeSetHead;
        }
        else
        {
            adjustImageVC.type = CTAdjustImageViewControllerTypeDefault;
        }
        
        UIImage * adjustImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        
      
//        NSData * imgData = UIImagePNGRepresentation(adjustImg);
//        long long int byteCount = imgData.length;
//        NSLog(@"%f",byteCount/(1024.0*1024.0*5.0));
//        adjustImg = [CTImageProcessing imageCompressionImg:adjustImg WithSize:CGSizeMake(1024, 1024)];
//        NSData * imgData1 = UIImagePNGRepresentation(adjustImg);
//        long long int byteCount1 = imgData1.length;
//        NSLog(@"%f",byteCount1/(1024.0*1024.0*5.0));
        
        adjustImageVC.adjustImage = adjustImg;
        
        [self.navigationController pushViewController:adjustImageVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
        
    }failureBlock:^(NSError *error){
        
    }];
}

-(void)cancelAction:(CTPickImageView *)view
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)cameraAction:(CTPickImageView *)view
{
    [self addCamera];
}

-(void)albumPickedViewShowAction:(CTPickImageView *)view withItem:(CTAlbumItem *)itm
{
    currentPickedItem = itm;
    [self pickAlbum:currentPickedItem];
}



#pragma mark - AssetsLibrary -

//初始化相册
-(void)initAlbumData
{
    dispatch_async(dispatch_get_main_queue(), ^{
        @try {
            __block NSInteger groupImgNumber;
            
            ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
            {
                [CTDebugManager showErrorLogInfo:[NSString stringWithFormat:@"相册访问失败 =%@", [myerror localizedDescription]]];
                if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {
                    [CTDebugManager showErrorLogInfo:@"无法访问相册.请在'设置->定位服务'设置为打开状态."];
                }else{
                    [CTDebugManager showErrorLogInfo:@"相册访问失败."];
                }
            };
            
            ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop)
            {
                if (isGroupEnumerAtion == YES) {
                    return ;
                }
                if (result!=NULL) {
                    
                    if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
                        
                        NSString *urlstr=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];//图片的url
                        // result.defaultRepresentation.fullScreenImage//图片的大图
                        // result.thumbnail                            //图片的缩略图小图
                        
                        [albumArray addObject:[UIImage imageWithCGImage:result.thumbnail]];
                        [albumFullScreenArray addObject:urlstr];
                        
                    }
                    
                    if (index == groupImgNumber-1) {
                        
                        isGroupEnumerAtion = YES;
                        
                        //初始化相机图片
                        UIImage * cameraImage = [UIImage imageNamed:@"camera_btn_pub"];
                        [albumArray addObject:cameraImage];
                        albumArray = (NSMutableArray *)[[albumArray reverseObjectEnumerator] allObjects];
                        
                        [albumFullScreenArray addObject:cameraImage];
                        albumFullScreenArray = (NSMutableArray *)[[albumFullScreenArray reverseObjectEnumerator] allObjects];
                        
                        pickImageView.imgArray = [albumArray copy];
                        pickImageView.imgFullScreenArray = [albumFullScreenArray copy];
                        
                        if (albumItemsArray.count != 0) currentPickedItem = [albumItemsArray objectAtIndex:0];
                        
                    }
                }
                
            };
            
            ALAssetsLibraryGroupsEnumerationResultsBlock
            libraryGroupsEnumeration = ^(ALAssetsGroup* group, BOOL* stop)
            {
                
                if (group!=nil)
                {
                    NSString *g=[NSString stringWithFormat:@"%@",group];//获取相簿的组
                    NSString *g1=[g substringFromIndex:16 ] ;
                    NSArray *arr=[[NSArray alloc] init];
                    arr=[g1 componentsSeparatedByString:@","];
                    NSString *g2=[[arr objectAtIndex:0] substringFromIndex:5];
                    if ([g2 isEqualToString:@"Camera Roll"]) {
                        g2=@"相机胶卷";
                    }
                    NSString *groupName=g2;//组的name
                    groupImgNumber = [group numberOfAssets];
                    
                    
                    CTAlbumItem * item = [[CTAlbumItem alloc] init];
                    item.group = group;
                    item.groupName = groupName;
                    item.imgNumber = [NSString stringWithFormat:@"%ld",(long)groupImgNumber];
                    if ([item.groupName isEqualToString:@"我的照片流"]==NO)
                    [albumItemsArray addObject:item];
                    
                    pickImageView.albumArray = albumItemsArray;
                    
                    [group enumerateAssetsUsingBlock:groupEnumerAtion];
                }
                
            };
            
            library = [[ALAssetsLibrary alloc] init];
            [library enumerateGroupsWithTypes:ALAssetsGroupAll
                                   usingBlock:libraryGroupsEnumeration
                                 failureBlock:failureblock];
        }
        @catch (NSException *exception) {
            
        }
    });
}

//选择相应相册
-(void)pickAlbum:(CTAlbumItem *)itm
{
    
    ALAssetsGroup * group = itm.group;
    NSInteger groupImgNumber = [itm.imgNumber integerValue];
    
    ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop)
    {
        
        if (result!=NULL) {
            
            if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
                
                NSString *urlstr=[NSString stringWithFormat:@"%@",result.defaultRepresentation.url];//图片的url
                
                [albumArray addObject:[UIImage imageWithCGImage:result.thumbnail]];
                [albumFullScreenArray addObject:urlstr];
            }
            
            if (index == groupImgNumber-1) {
                
                
                //初始化相机图片
                UIImage * cameraImage = [UIImage imageNamed:@"camera_btn_pub"];
                [albumArray addObject:cameraImage];
                albumArray = (NSMutableArray *)[[albumArray reverseObjectEnumerator] allObjects];
                
                [albumFullScreenArray addObject:cameraImage];
                albumFullScreenArray = (NSMutableArray *)[[albumFullScreenArray reverseObjectEnumerator] allObjects];
                
                pickImageView.imgArray = [albumArray copy];
                pickImageView.imgFullScreenArray = [albumFullScreenArray copy];
                
            }
        }
        
    };
    
    [albumArray removeAllObjects];
    [albumFullScreenArray removeAllObjects];
    
    [group enumerateAssetsUsingBlock:groupEnumerAtion];
}


//存入指定相册
-(void)addAssetURL:(NSURL*)assetURL toAlbum:(NSString*)albumName withCompletionBlock:(SaveImageCompletion)completionBlock
{
    //相册存在标示
    __block BOOL albumWasFound = NO;
    
    ALAssetsLibrary *assetsLibrary = library;
    //search all photo albums in the library
 
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop)
     {
         
         //判断相册是否存在
         if ([albumName compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame) {
             
             //存在
             albumWasFound = YES;
             
             //get a hold of the photo's asset instance
             [assetsLibrary assetForURL: assetURL
                            resultBlock:^(ALAsset *asset) {
                                
                                //add photo to the target album
                                [group addAsset: asset];
                                
                                //run the completion block
                                completionBlock(nil);
                                
                            } failureBlock: completionBlock];
             return;
         }
         
         //如果不存在该相册创建
         if (group==nil && albumWasFound==NO)
         {
             __weak ALAssetsLibrary* weakSelf = assetsLibrary;
             
             //创建相册
             [assetsLibrary addAssetsGroupAlbumWithName:albumName resultBlock:^(ALAssetsGroup *group)
              {
                  
                  //get the photo's instance
                  [weakSelf assetForURL: assetURL
                            resultBlock:^(ALAsset *asset)
                   {
                       
                       //add photo to the newly created album
                       [group addAsset: asset];
                       
                       //call the completion block
                       completionBlock(nil);
                       
                   } failureBlock: completionBlock];
                  
              } failureBlock: completionBlock];
             return;
         }
         
     }failureBlock:completionBlock];
}







-(void)addCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }else{
        CTRemindView * remindView = [[CTRemindView alloc] init];
        [remindView showRemindViewOn:self.view withRemindWord:[CTAppLanguage localizedStringForKey:@"remindView_noCamera" withValue:nil withTable:@"Language"]];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    
//    self.hidesBottomBarWhenPushed = YES;
//    CTAdjustImageViewController * adjustImageVC = [[CTAdjustImageViewController alloc] init];
//    adjustImageVC.adjustImage = image;
//    [self.navigationController pushViewController:adjustImageVC animated:YES];
//    self.hidesBottomBarWhenPushed = NO;
    self.hidesBottomBarWhenPushed = YES;
    
    CTAdjustImageViewController * adjustImageVC = [[CTAdjustImageViewController alloc] init];
    if (type == CTPickImageViewControllerTypeSetHead)
    {
        adjustImageVC.type = CTAdjustImageViewControllerTypeSetHead;
    }
    else
    {
        adjustImageVC.type = CTAdjustImageViewControllerTypeDefault;
    }
    adjustImageVC.adjustImage = image;
    
    
    
//    [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
    [self.navigationController pushViewController:adjustImageVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
    //图片存入相册
    [self saveImageToAlbum:[CTAppInfo appName] withImage:image];
}

-(void)saveImageToAlbum:(NSString *)name withImage:(UIImage *)img
{
    
    __weak CTPickImageViewController * vc = self;
    __weak CTAlbumItem * item = currentPickedItem;
    
    [library writeImageToSavedPhotosAlbum:img.CGImage orientation:(ALAssetOrientation)img.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
        [self addAssetURL:assetURL toAlbum:name withCompletionBlock:^{
            [vc dismissViewControllerAnimated:YES completion:^{
                [vc pickAlbum:item];
            }];
        }];
    }];
}

@end
